
package com.example.antitouchscreen;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class FloatingService extends Service implements View.OnClickListener{

    private WindowManager windowManager;
    private View floatingView;
    private WindowManager.LayoutParams layoutParams;
    private Button bt_close,bt_close_after,bt_cancel;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        // 加载悬浮窗的布局
        floatingView = LayoutInflater.from(this).inflate(R.layout.activity_floating, null);
        bt_close=floatingView.findViewById(R.id.close);
//        bt_close_after=floatingView.findViewById(R.id.close_after);
        bt_cancel=floatingView.findViewById(R.id.cancel);
        bt_close.setOnClickListener(this);
//        bt_close_after.setOnClickListener(this);
        bt_cancel.setOnClickListener(this);

        // 设置悬浮窗的布局参数
        layoutParams = new WindowManager.LayoutParams(
                // 设置悬浮窗的宽度为屏幕宽度的50%
//                (int) (windowManager.getDefaultDisplay().getWidth() * 0.5f),
                // 设置悬浮窗的高度为屏幕高度的50%
//                (int) (windowManager.getDefaultDisplay().getHeight() * 0.5f),
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
//        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.gravity = Gravity.CENTER;

        // 将悬浮窗添加到WindowManager
        windowManager.addView(floatingView, layoutParams);

        // 屏蔽滑动
        floatingView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 检查是否是滑动手势
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    // 对于滑动事件，返回 true 来阻止它
                    return true;
                } else {
                    // 对于其他事件，返回 false 或者执行你自己的逻辑
                    return false; // 这会让点击等其他事件正常工作
                }
            }
        });

//        // 屏蔽滑动
//        floatingView.setOnTouchListener(new View.OnTouchListener() {
//            private static final int MAX_CLICK_DURATION = 200; // 最大点击持续时间（毫秒）
//            private long startClickTime;
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        // 记录按下时间
//                        startClickTime = System.currentTimeMillis();
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        // 计算按下和抬起的时间差
//                        long clickDuration = System.currentTimeMillis() - startClickTime;
//                        if (clickDuration < MAX_CLICK_DURATION) {
//                            // 如果时间差小于最大点击持续时间，则视为点击事件
//                            // 这里可以处理点击事件
//                        }
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        // 计算移动距离
//                        float dx = event.getX() - v.getX();
//                        float dy = event.getY() - v.getY();
//                        if (Math.abs(dx) > 10 || Math.abs(dy) > 10) {
//                            // 如果移动距离大于10像素，则视为滑动事件，并阻止
//                            return true;
//                        }
//                        break;
//                }
//                // 对于长按事件，返回false，允许系统处理
//                return false;
//            }
//        });



        // 设置悬浮窗的触摸监听，以便可以拖动悬浮窗（可根据需求完善拖动逻辑）
//        floatingView.setOnTouchListener(new View.OnTouchListener() {
//            private int initialX;
//            private int initialY;
//            private float initialTouchX;
//            private float initialTouchY;
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        initialX = layoutParams.x;
//                        initialY = layoutParams.y;
//                        initialTouchX = event.getRawX();
//                        initialTouchY = event.getRawY();
//                        return true;
//                    case MotionEvent.ACTION_MOVE:
//                        layoutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
//                        layoutParams.y = initialY + (int) (event.getRawY() - initialTouchY);
//                        windowManager.updateViewLayout(floatingView, layoutParams);
//                        return true;
//                    case MotionEvent.ACTION_UP:
//                        return false;
//                    default:
//                        return false;
//                }
//            }
//        });

        // 设置长按监听来弹出菜单
        floatingView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                Function_SharePreference sp=new Function_SharePreference(getApplicationContext());
                String show=sp.get("isShow");
                if(show.equals("true")){
                    bt_close.setVisibility(View.VISIBLE);
//                bt_close_after.setVisibility(View.VISIBLE);
                    bt_cancel.setVisibility(View.VISIBLE);
                    showPopupMenu(v);
                }

                MyLog.d("进入了长按菜单监听");
                return true;
            }
        });
    }

    private void showPopupMenu(View view) {



        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenuInflater().inflate(R.menu.floating_menu, popupMenu.getMenu());


        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.close:
                        stopSelf();
                        break;
//                    case R.id.close_after_5_seconds:
//                        new Thread(() -> {
//                            try {
//                                Thread.sleep(5000);
//                                stopSelf();
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }).start();
//                        break;
                    case R.id.cancel:
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (windowManager!= null && floatingView!= null) {
            windowManager.removeView(floatingView);
        }
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                stopSelf();
                break;
//            case R.id.close_after:
//                bt_close.setVisibility(View.GONE);
//                bt_close_after.setVisibility(View.GONE);
//                bt_cancel.setVisibility(View.GONE);
//                new Thread(() -> {
//                    try {
//                        Thread.sleep(5000);
//                        stopSelf();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }).start();
//                break;
            case R.id.cancel:
                bt_close.setVisibility(View.GONE);
//                bt_close_after.setVisibility(View.GONE);
                bt_cancel.setVisibility(View.GONE);
                break;

        }
    }
}